package com.cloud.phone.utils

import android.net.VpnService
import com.blankj.utilcode.util.SPUtils
import com.cloud.phone.constants.Constants
import engine.Engine
import java.net.InetAddress
import java.net.UnknownHostException

/**
 * @auth: njb
 * @date: 2024/6/5 9:46
 * @desc: 描述
 */
object ProxyUtils {
    const val TAG = "ProxyUtils"

    /**
     * Computes the inverted subnet, routing all traffic except to the specified subnet. Use prefixLength
     * of 32 or 128 for a single address.
     *
     * @see [](https://stackoverflow.com/a/41289228)
     */
    fun addRoutesExcept(builder: VpnService.Builder, address: String?, prefixLength: Int) {
        try {
            val bytes = InetAddress.getByName(address).address
            for (i in 0 until prefixLength) { // each entry
                val res = ByteArray(bytes.size)
                for (j in 0..i) { // each prefix bit
                    res[j / 8] =
                        (res[j / 8].toInt() or (bytes[j / 8].toInt() and (1 shl 7 - j % 8))).toByte()
                }
                res[i / 8] = (res[i / 8].toInt() xor (1 shl 7 - i % 8)).toByte()
                builder.addRoute(InetAddress.getByAddress(res), i + 1)
            }
        } catch (e: UnknownHostException) {
            throw RuntimeException(e)
        }
    }


    fun startProxy(){
        Engine.start()
    }

    fun stopProxy(){
        Engine.stop()
    }

    fun ProxySocks(username:String, password:String, ip:String, port:Int):String{
        return String.format("%s:%s@%s:%s", username, password, ip, port)
    }

    fun setSocksUrl(url:String){
        SPUtils.getInstance().put(Constants.SOCKS5_RUL, url)
    }

    fun getSocksUrl():String{
        return SPUtils.getInstance().getString(Constants.SOCKS5_RUL, "");
    }

    fun setTaskId(id:String){
        SPUtils.getInstance().put(Constants.TASK_ID,id)
    }

    fun getTaskId():String{
        return SPUtils.getInstance().getString(Constants.TASK_ID,"")
    }

    fun setVpnPermission(isVpn:Boolean){
        SPUtils.getInstance().put(Constants.IS_VPN_PERMISSION_OPEN,isVpn)
    }

    fun getVpnPermission():Boolean{
       return SPUtils.getInstance().getBoolean(Constants.IS_VPN_PERMISSION_OPEN,false)
    }

    fun setProxyIp(ip:String){
        SPUtils.getInstance().put(Constants.PROXY_IP,ip)
    }

    fun getProxyIp():String{
        return SPUtils.getInstance().getString(Constants.PROXY_IP,"")
    }
}